import React, { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import ThemeToggle from '../components/ui/ThemeToggle';

const ChangePasswordPage: React.FC = () => {
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [validationError, setValidationError] = useState('');
  const [success, setSuccess] = useState(false);
  const { user, changePassword, isLoading, error, clearError } = useAuth();
  const navigate = useNavigate();

  // 如果用户未登录，重定向到登录页
  React.useEffect(() => {
    if (!user) {
      navigate('/login');
    }
  }, [user, navigate]);

  const validateForm = () => {
    if (!currentPassword.trim()) {
      setValidationError('请输入当前密码');
      return false;
    }
    
    if (!newPassword.trim()) {
      setValidationError('请输入新密码');
      return false;
    }
    
    if (newPassword.length < 6) {
      setValidationError('新密码至少需要6个字符');
      return false;
    }
    
    if (newPassword !== confirmPassword) {
      setValidationError('两次输入的新密码不一致');
      return false;
    }
    
    if (currentPassword === newPassword) {
      setValidationError('新密码不能与当前密码相同');
      return false;
    }
    
    setValidationError('');
    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }

    try {
      await changePassword(currentPassword, newPassword, confirmPassword);
      setSuccess(true);
      // 清空表单
      setCurrentPassword('');
      setNewPassword('');
      setConfirmPassword('');
      
      // 3秒后跳转到首页
      setTimeout(() => {
        navigate('/');
      }, 3000);
    } catch (error) {
      // 错误已经在AuthContext中处理
    }
  };

  const handleInputChange = () => {
    if (error) {
      clearError();
    }
    if (validationError) {
      setValidationError('');
    }
    if (success) {
      setSuccess(false);
    }
  };

  const displayError = error || validationError;

  if (!user) {
    return null; // 或者显示加载状态
  }

  return (
    <div className="min-h-screen flex items-center justify-center p-4">
      <div className="fixed top-4 right-4">
        <ThemeToggle />
      </div>
      <div className="card w-full max-w-md bg-base-100 shadow-xl">
        <div className="card-body">
          <div className="text-center mb-6">
            <h1 className="text-3xl font-bold text-base-content site-title mb-2">修改密码</h1>
            <p className="text-base-content/70">为了您的账户安全，请定期更换密码</p>
          </div>
        
        {success && (
          <div className="alert alert-success mb-4">
            <span>密码修改成功！3秒后将跳转到首页...</span>
          </div>
        )}
        
        {displayError && (
          <div className="alert alert-error mb-4">
            <span>{displayError}</span>
          </div>
        )}
        
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="form-control">
            <label className="label" htmlFor="currentPassword">
              <span className="label-text">当前密码</span>
            </label>
            <input
              type="password"
              id="currentPassword"
              value={currentPassword}
              onChange={(e) => {
                setCurrentPassword(e.target.value);
                handleInputChange();
              }}
              placeholder="请输入当前密码"
              className="input w-full"
              required
              disabled={isLoading || success}
            />
          </div>
          
          <div className="form-control">
            <label className="label" htmlFor="newPassword">
              <span className="label-text">新密码</span>
            </label>
            <input
              type="password"
              id="newPassword"
              value={newPassword}
              onChange={(e) => {
                setNewPassword(e.target.value);
                handleInputChange();
              }}
              placeholder="请输入新密码（至少6个字符）"
              className="input w-full"
              required
              disabled={isLoading || success}
            />
          </div>
          
          <div className="form-control">
            <label className="label" htmlFor="confirmPassword">
              <span className="label-text">确认新密码</span>
            </label>
            <input
              type="password"
              id="confirmPassword"
              value={confirmPassword}
              onChange={(e) => {
                setConfirmPassword(e.target.value);
                handleInputChange();
              }}
              placeholder="请再次输入新密码"
              className="input w-full"
              required
              disabled={isLoading || success}
            />
          </div>
          
          <button 
            type="submit" 
            className={`btn btn-primary w-full ${isLoading ? 'loading' : ''}`}
            disabled={isLoading || success || !currentPassword.trim() || !newPassword.trim() || !confirmPassword.trim()}
          >
            {isLoading ? '修改中...' : success ? '修改成功' : '修改密码'}
          </button>
        </form>
        
        <div className="divider"></div>
        
        <div className="text-center">
          <Link to="/" className="btn btn-ghost">返回首页</Link>
        </div>
        </div>
      </div>
    </div>
  );
};

export default ChangePasswordPage;